package org.yxing.palpalgps.activity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.yxing.palpalgps.AbstractActivity;
import org.yxing.palpalgps.R;
import org.yxing.palpalgps.adapter.BlackListAdapter;
import org.yxing.palpalgps.http.AsyncRequest;
import org.yxing.palpalgps.http.AsyncRequest.FetchListener;
import org.yxing.palpalgps.models.BlackList;
import org.yxing.palpalgps.models.User;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

/**
 * 
 * @author yuxing
 *
 */
public class BlackListActivity extends AbstractActivity implements OnItemClickListener{
    
    private ListView mListView;
    private BlackListAdapter adapter;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle(getString(R.string.blacklist));
        setContentView(R.layout.black_list);
        
        mListView = (ListView) findViewById(android.R.id.list);
        adapter = new BlackListAdapter(this);
        
        mListView.setAdapter(adapter);
        mListView.setOnItemClickListener(this);
        
        fetchData();
    }
    
    /**
     * fetch data
     */
    private void fetchData() {
        AsyncRequest ar = new AsyncRequest(this);
        ar.fetch("blacklist/list", new FetchListener() {
            
            public void onError(int code, String msg) {
                
            }
            
            public void onComplete(JSONObject response) {
                try {
                    JSONArray result = response.getJSONArray("result");
                    for (int i = 0; i < result.length(); i ++) {
                        JSONObject json = result.getJSONObject(i);
                        BlackList blackList = new BlackList();
                        blackList.setUid(json.getString(User.KEY_UID));
                        blackList.setName(json.getString(User.KEY_NAME));
                        blackList.setPortrait(json.getString(User.KEY_FACE));
                        adapter.add(blackList);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        displayToast("" + position);
    }
    
    
}
